﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using HtmlAgilityPack;
using Soufun.DAL;
using Soufun.DB;
using Soufun.Model;

namespace Soufun
{
    public partial class AreaAnalysisFrom : Form
    {
        public AreaAnalysisFrom()
        {
            InitializeComponent();
        }

        private List<ProjectInfo> projectInfos = new List<ProjectInfo>();
        private DProject _dProject = new DProject();
        private string _strTablePath =
         "//html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[2]/table[1]" +
          "/tbody[1]" +
         "/tr[2]/td[1]/table[2]" +
          "/tbody[1]" +
         "/tr[1]/td[1]/table[1]" +
          "/tbody[1]" +
          "/tr[3]/td[1]/table[1]" +
          "/tbody[1]" +
          "/tr[1]/td[1]/table[2]/tbody[1]/tr";
        private string _strNamePath = "//tr[1]/td[1]/a[1]/span[1]";
        private string _strAmountPath = "//tr[1]/td[2]";
        private string _strHousingSoldPath = "//tr[1]/td[3]";
        private string _strHousingCanSellPath = "//tr[1]/td[4]";
        private string _strNonHousingSoldPath = "//tr[1]/td[5]";
        private string _strNonHousingCanSellPath = "//tr[1]/td[6]";

        private string _selectedArea;
        private string _selectedTimeA;
        private string _selectedTimeB;
        private bool _isCatchAll;

        private void AreaAnalysisFrom_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(BindControlData){IsBackground = true};
            t.Start();
        }

        private void BindControlData()
        {
            int areaId = int.Parse(comboBox_seleceAreaList.Properties.Items[
                   comboBox_seleceAreaList.SelectedIndex].Value.ToString());
            string strWhere = "";
            if (areaId!=100)
            {
                strWhere = "AreaNameID=" + areaId;
            }
            DataSet ds = _dProject.GetListOfInsertTime(strWhere);
            if (ds==null || ds.Tables.Count==0)
            {
                XtraMessageBox.Show("数据库连接故障，请检测！");
                return;
            }
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_startTime.Properties.Items.Clear();
                comboBox_endTime.Properties.Items.Clear();
            }));
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string insertTime = row["InsertTime"].ToString();
                ImageComboBoxItem item = new ImageComboBoxItem();
                item.Description = insertTime;
                item.Value = insertTime;
                BeginInvoke(new MethodInvoker(() =>
                    {
                        comboBox_startTime.Properties.Items.Add(item);
                        comboBox_endTime.Properties.Items.Add(item);
                    }));
            }
            BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_startTime.Enabled = true;
                    comboBox_endTime.Enabled = true;
            }));
        }

        private void btn_storeData_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("确定抓取数据？","提醒：",
                MessageBoxButtons.YesNo)== DialogResult.No)
            {
                return;
            }

            string strArea = comboBox_areaList.SelectedItem.ToString();
             
            comboBox_areaList.Enabled = false;
            btn_storeData.Enabled = false;
            progressBar1.Visible = true;
            label_progressNotice.Visible = true;

            Thread getAreaDataThread = new Thread(GetAreaData) { IsBackground = true };
            getAreaDataThread.Start(strArea);
        }

        private void btn_select_Click(object sender, EventArgs e)
        {            
            if (!CheckedPass())
            {
                return;
            }
            _selectedArea = comboBox_areaList.SelectedItem.ToString();
            _selectedTimeA = comboBox_startTime.SelectedItem.ToString();
            _selectedTimeB = comboBox_endTime.SelectedItem.ToString();
            gridControl1.DataSource = null;
            searchLookUpEdit1.Properties.DataSource = null;
            gridView1.GroupPanelText = "正在加载数据...";
            Thread t = new Thread(BindDataInThread){IsBackground = true};
            t.Start();
        }
         
        private void BindDataInThread()
        {
            try
            {
                int areaId = int.Parse(comboBox_areaList.Properties.Items[
                    comboBox_areaList.SelectedIndex].Value.ToString());
                DataSet ds = _dProject.GetCountResultOfTwoDateTime(
                    areaId, _selectedTimeA, _selectedTimeB);
                BeginInvoke(new MethodInvoker(() =>
                    {
                        gridControl1.DataSource = ds.Tables[0];
                        searchLookUpEdit1.Properties.DataSource =ds.Tables[0];
                        gridView1.GroupPanelText = "查询结果";
                    }));                 
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载数据出现异常：" + ex.Message);
            }
        }

        

        private void GetAreaData(object areaNameObject)
        {
            DateTime timeStart = DateTime.Now;
            string areaName = areaNameObject.ToString();
            projectInfos.Clear();
            if (areaName=="所有地区")
            {
                areaName = "";
                _isCatchAll = true;               
            }
            else
            {
                _isCatchAll = false;              
            }
            BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_areaList.Enabled = false;
                    btn_storeData.Enabled = false;
                }));
            GetSingleAreaData(areaName);
            TimeSpan span  = DateTime.Now - timeStart;
            Console.WriteLine("==========耗时"+span.Seconds+"秒==========");
        }

        private void GetSingleAreaData(string areaName)
        {
            Console.WriteLine("正在获取第1页数据。");
            BeginInvoke(new MethodInvoker(()
                => label_progressNotice.Text = "正在获取第1页数据..."));
            int pageCount = 1;
            string url = GetWebUrl(1, areaName);
            string httpText = Common.GetHtmlTextByUrl(url);
            //获取总页数
            string tmpstring = "条，共搜索到<FONT color=#FF0000>";
            int index = httpText.IndexOf(tmpstring);
            int pageIndex = index + tmpstring.Length;
            int endIndex = httpText.IndexOf("<", pageIndex);
            pageCount = int.Parse(httpText.Substring(pageIndex, endIndex - pageIndex));
            //获取总条数
            tmpstring = "共搜索到</FONT><FONT color=#FF0000>";
            index = httpText.IndexOf(tmpstring);
            int rowsIndex = index + tmpstring.Length;
            int rowEndInde = httpText.IndexOf("<", rowsIndex);
            int rowsCount = int.Parse(httpText.Substring(rowsIndex, rowEndInde - rowsIndex));

            BeginInvoke(new MethodInvoker(()
                                          =>
            { 
                progressBar1.Properties.Minimum = 0;
                progressBar1.Properties.Maximum = rowsCount;
                progressBar1.Position = 0;    
                            
                label_progressNotice.Text = "找到" + rowsCount
                    + "条数据,共计" + pageCount + "页"
                    + ",开始获取第一页数据..";
            }));


            AnalysisHtmlStringToProjectInfo(httpText);


            for (int i = 2; i <= pageCount; i++)
            {
                Console.WriteLine("正在获取第" + i.ToString() + "页数据。");
                BeginInvoke(new MethodInvoker(()
                                         =>
                {
                    label_progressNotice.Text = "找到" + rowsCount
                        + "条数据,共计" + pageCount + "页"
                        + ",正在获取" + i + "页数据..";
                }));
                string url2 = GetWebUrl(i, areaName);
                string httpText2 = Common.GetHtmlTextByUrl(url2);
                AnalysisHtmlStringToProjectInfo(httpText2);
            }


            if (projectInfos.Count > 0)
            {
                Console.WriteLine("正在保存数据到本地");
                BeginInvoke(new MethodInvoker(()
                                        =>
                {
                    //progressBar1.Position = rowsCount;
                    label_progressNotice.Text = "数据获取完成,正在保存到数据库..";
                }));

                DateTime insertTime = DateTime.Now;
                //int inertTimes = int.Parse(
                //Math.Ceiling(((double)projectInfos.Count / 50)).ToString());
                //for (int i = 0; i < inertTimes; i++)
                //{
                int succeedrows = 0;
                int insertRowsCount = 500;
                StringBuilder strSql = new StringBuilder();
                for (int i = 0; i < projectInfos.Count; i++)
                {
                    ProjectInfo projectInfo = projectInfos[i];
                    if (i%insertRowsCount==0)
                    {
                        strSql = new StringBuilder();
                        // strSql.Append("set names  'uft8';");
                        strSql.Append("Insert into tAreaAnalyze (");
                        strSql.Append("AreaNameID,ProjectName,Amount,");
                        strSql.Append("HousingSoldCount,HousingOnSaleCount,");
                        strSql.Append("NonHousingSoldCount,NonHousingOnSaleCount,");
                        strSql.Append("InsertTime)");
                        strSql.Append(" value ");                        
                    }
                    strSql.Append("(");
                    strSql.Append(projectInfo.AreaNameID);
                    strSql.Append(",'");

                    string strName = projectInfo.ProjectName;
                    strName = strName.Replace("'", " ");
                    strName = strName.Replace(";", " ");
                    strName = strName.Replace("1=1", " ");
                    strName = strName.Replace("|", " ");
                    strName = strName.Replace("<", " ");
                    strName = strName.Replace(">", " ");
                    strName = strName.Replace("．", "·");
                    strSql.Append(strName);
                    strSql.Append("',");
                    strSql.Append(projectInfo.Amount);
                    strSql.Append(",");
                    strSql.Append(projectInfo.HousingSoldCount);
                    strSql.Append(",");
                    strSql.Append(projectInfo.HousingOnSaleCount);
                    strSql.Append(",");
                    strSql.Append(projectInfo.NonHousingSoldCount);
                    strSql.Append(",");
                    strSql.Append(projectInfo.NonHousingOnSaleCount);
                    strSql.Append(",'");
                    strSql.Append(insertTime);
                    strSql.Append("'),");
                    if ((i + 1)%insertRowsCount == 0 || i==projectInfos.Count-1)
                    {
                        strSql.Remove(strSql.Length - 1, 1);
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                }
                    
                   
                //}
             
               
                BeginInvoke(new MethodInvoker(()
                                     =>
                {
                    if (succeedrows == rowsCount)
                    {
                        label_progressNotice.Text = "数据抓取保存成功！";
                        //ImageComboBoxItem item = new ImageComboBoxItem();
                        //item.Description = 
                    }
                    else
                    {
                        int failedCount = rowsCount - succeedrows;
                        label_progressNotice.Text = failedCount + "条数据保存失败！请检测数据库连接是否正常";
                    }
                    comboBox_areaList.Enabled = true;
                    btn_storeData.Enabled = true;
                }));

            }
        }


        private void AnalysisHtmlStringToProjectInfo(string httpText)
        {
            
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(httpText);
            HtmlNode rootNode = document.DocumentNode;
            HtmlNodeCollection categoryNodeList = rootNode.SelectNodes(_strTablePath);
            HtmlNode temp = null;
            if (categoryNodeList == null)
            {
                return;
            }
            for (int i = 0; i < categoryNodeList.Count; i++)
            {
                if (i < 2)
                {
                    continue;
                }
                ProjectInfo model = new ProjectInfo();
                 
                model.AreaNameID =
                    int.Parse(comboBox_areaList.Properties.Items[
                    comboBox_areaList.SelectedIndex].Value.ToString());

                temp = HtmlNode.CreateNode(categoryNodeList[i].OuterHtml);
                HtmlNode nodeProject = temp.SelectSingleNode(_strNamePath);
                if (nodeProject != null)
                {
                    model.ProjectName = nodeProject.InnerText;                     
                }
                HtmlNode nodeAmount = temp.SelectSingleNode(_strAmountPath);
                if (nodeAmount != null)
                {
                    string amount = nodeAmount.InnerText.Replace("&nbsp;", "");
                    if (amount == "-")
                    {
                        amount = "0";
                    }
                    int intValue = 0;
                    int.TryParse(amount, out intValue);
                    model.Amount = intValue;
                }
                HtmlNode node1 = temp.SelectSingleNode(_strHousingSoldPath);
                if (node1 != null)
                {
                    string houseSold = node1.InnerText.Replace("&nbsp;", "");
                    int intValue = 0;
                    int.TryParse(houseSold, out intValue);
                    model.HousingSoldCount = intValue;
                }
                HtmlNode node2 = temp.SelectSingleNode(_strHousingCanSellPath);
                if (node2 != null)
                {
                    string strValue = node2.InnerText.Replace("&nbsp;", "");
                    int intValue = 0;
                    int.TryParse(strValue, out intValue);
                    model.HousingOnSaleCount = intValue;
                }
                HtmlNode node3 = temp.SelectSingleNode(_strNonHousingSoldPath);
                if (node3 != null)
                {
                    string strValue = node3.InnerText.Replace("&nbsp;", "");
                    int intValue = 0;
                    int.TryParse(strValue, out intValue);
                    model.NonHousingSoldCount = intValue;
                }
                HtmlNode node4 = temp.SelectSingleNode(_strNonHousingCanSellPath);
                if (node4 != null)
                {
                    string strValue = node4.InnerText.Replace("&nbsp;", "");
                    int intValue = 0;
                    int.TryParse(strValue, out intValue);
                    model.NonHousingOnSaleCount = intValue;
                }
                projectInfos.Add(model);
                 
                BeginInvoke(new MethodInvoker(()
                                         =>
                {

                    progressBar1.Position ++;
                    
                }));
           
            }
        }


        private string GetWebUrl(int page, string area)
        {
            string webUrl = "http://scxx.whfcj.gov.cn/xmqk.asp?page=" + page
                + "&domain=" + Common.UrlEncode(area) + "&blname=&bladdr=&prname=";
            return webUrl;
        }

        private void comboBox_areaList_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox_startTime.Enabled = false;
            comboBox_endTime.Enabled = false;
            Thread t = new Thread(BindControlData){IsBackground = true};
            t.Start();
        }

        private bool CheckedPass()
        {
            if (comboBox_startTime.SelectedItem == null)
            {
                XtraMessageBox.Show("请选择对比时间！");
                comboBox_startTime.Focus();
                return false;
            }
            if (comboBox_endTime.SelectedItem == null)
            {
                XtraMessageBox.Show("请选择对比时间！");
                comboBox_endTime.Focus();
                return false;
            }
            string startTime = comboBox_startTime.SelectedItem.ToString();
            string endTime = comboBox_endTime.SelectedItem.ToString();
            if (DateTime.Parse(startTime)>=DateTime.Parse(endTime))
            {
                XtraMessageBox.Show("起始时间应小于结束时间！");
                comboBox_startTime.Focus();
                return false;
            }
            return true;
        }

       
        private void btn_exportToExcel_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                return;
            }
            if (_selectedTimeA == null && _selectedTimeB == null)
            {
                XtraMessageBox.Show("尚无对比结果，请查询结果后再做导出！");
                return;
            }

            saveFileDialog1.FileName =_selectedArea + "项目情况比较(" +
                DateTime.Parse(_selectedTimeB).ToString("yy年MM月dd日HH点mm分")
                + "对比" +
                DateTime.Parse(_selectedTimeA).ToString("yy年MM月dd日HH点mm分")
                + ")";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }




        #region 窗体效果
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.btn_exit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.btn_exitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {            
            Close();
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.Close();
            }
        }

        #endregion

        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            DevExpress.Utils.AppearanceDefault appRed = new DevExpress.Utils.AppearanceDefault
               (Color.Black, Color.DarkGray, Color.Empty, Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Horizontal);
            DevExpress.Utils.AppearanceDefault appYellow = new DevExpress.Utils.AppearanceDefault
                (Color.Black, Color.Yellow, Color.Empty, Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Horizontal);
            DevExpress.Utils.AppearanceDefault appGreen = new DevExpress.Utils.AppearanceDefault
                (Color.Black, Color.LimeGreen, Color.Empty, Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Horizontal);

            if (e.Column.FieldName == "a4" || e.Column.FieldName == "b4"||
                e.Column.FieldName == "a2" || e.Column.FieldName == "b2")
            {
                
               DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, appYellow);             
            }
            else if (e.Column.FieldName == "a1" || e.Column.FieldName == "a3" ||
                e.Column.FieldName == "b1" || e.Column.FieldName == "b3")
            {
             
                DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, appGreen);
            }
            else if (e.Column.FieldName == "a0" || e.Column.FieldName == "b0")
            {

                DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, appRed);
            }
        }


       

        
    }
}
